package com.splant.android.smart.UILevel.Community.fragments;

import android.app.Fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.DetectorListBean;
import com.splant.android.smart.ModelLevel.WaterListBean;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/21.
 */

public class Garden_DetectorList_Devices_Fragment extends Fragment implements View.OnClickListener{

    private static final int REQUEST_COUNT = 3;
    private String areaId="";

    private List<AreaListBean.Area> areaList = new ArrayList<>();
    private boolean isGetAreaId = false;

    private sPlantAsyncHttpClient sPlantClient;
    private View mView;
    private LRecyclerView lrv_detectorList;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private Garden_DetectorList_Device_Adapter garden_detectorList_devices_adapter;
    private List<DetectorListBean.Detector> detectorList = new ArrayList<>();

    private TextView tv_areaName;
    private boolean isLoadFinish;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.garden_detectorlist_devices_fragment,null);
            lrv_detectorList = (LRecyclerView) mView.findViewById(R.id.lrv_detectorList);
            tv_areaName= (TextView) mView.findViewById(R.id.tv_areaName);

            sPlantClient = sPlantAsyncHttpClient.getInstance();

            init();

            tv_areaName.setOnClickListener(this);
        }
        if (isLoadFinish==false)
            getDatas();

        return mView;
    }
    private void init()
    {
        garden_detectorList_devices_adapter = new Garden_DetectorList_Device_Adapter(getActivity());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(garden_detectorList_devices_adapter);

        lrv_detectorList.setHasFixedSize(true);
        lrv_detectorList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        lrv_detectorList.setAdapter(lRecyclerViewAdapter);
        lrv_detectorList.setRefreshProgressStyle(ProgressStyle.BallClipRotateMultiple);


       // lrv_detectorList.setFooterViewColor(R.color.colorAccent, R.color.garden_color2 ,android.R.color.white);
        lrv_detectorList.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");
        lrv_detectorList.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        lrv_detectorList.setOnRefreshListener(onRefreshListener);

        lrv_detectorList.setOnLoadMoreListener(onLoadMoreListener);
    }

    public void getDatas() {

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        params.put("pageNo", pageNo);
        params.put("pageSize", REQUEST_COUNT);
        params.put("isAutoTimer", 0);

        if (areaId.equals("") == false)
            params.put("areaId", areaId);

        sPlantClient.get(sPlantAsyncHttpClient.GETDETECTORDEVICES, params, new sPlantJsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try
                {
                    if (response.getInt("succeed") == 1) {

                        isLoadFinish=true;
                        Gson gson = new Gson();
                        DetectorListBean detectorListBean = gson.fromJson(response.toString(), DetectorListBean.class);

                        if (detectorListBean.getDetectorList() != null)
                        detectorList.addAll(detectorListBean.getDetectorList());

                        garden_detectorList_devices_adapter.setDataList(detectorList);

                        if (detectorListBean.getDetectorList() == null||detectorListBean.getDetectorList().size() < REQUEST_COUNT)
                            lrv_detectorList.setNoMore(true);

                        lrv_detectorList.refreshComplete(REQUEST_COUNT);
                    }

                } catch (Exception e) {
                    lrv_detectorList.refreshComplete(REQUEST_COUNT);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                lrv_detectorList.refreshComplete(REQUEST_COUNT);
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });

    }


    private OnRefreshListener onRefreshListener=new OnRefreshListener() {
        @Override
        public void onRefresh() {
            pageNo=0;
            detectorList.clear();
            lrv_detectorList.setNoMore(false);
            getDatas();
        }
    };
    private int pageNo = 0;
    private OnLoadMoreListener onLoadMoreListener=new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            pageNo += 1;
            lrv_detectorList.setNoMore(false);
            getDatas();
        }
    };

    private void showAreaList() {
        if (isGetAreaId)
            return;

        isGetAreaId = true;

        View popupView =getActivity().getLayoutInflater().inflate(R.layout.garden_arealist_popupwindow, null);

        final ListView lv_areaList = (ListView) popupView.findViewById(R.id.lv_areaList);

        final PopupWindow window = new PopupWindow(popupView, System_Dimen_Util.dip2px(getActivity(), 200), System_Dimen_Util.dip2px(getActivity(), 400));

        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));

        window.setFocusable(true);

        window.setOutsideTouchable(true);

        window.showAsDropDown(tv_areaName, 0, 2);

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        lv_areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                window.dismiss();
                areaId = areaList.get(position).getAreaId();
                tv_areaName.setText(areaList.get(position).getAreaName());
                pageNo=0;
                detectorList.clear();
                lrv_detectorList.setNoMore(false);
                getDatas();

            }
        });

        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    isGetAreaId = false;
                    if (response.getInt("succeed") == 1) {

                        Gson gson = new Gson();
                        AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);

                        if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0) {

                            areaList.clear();
                            AreaListBean.Area areaAll = new AreaListBean.Area();
                            areaAll.setAreaId("");
                            areaAll.setAreaName("全部区域");

                            areaList.add(areaAll);
                            areaList.addAll(areaListBean.getAreaList());

                            Garden_AreaList_Adapter garden_areaList_adapter = new Garden_AreaList_Adapter(getActivity(), areaList);

                            lv_areaList.setAdapter(garden_areaList_adapter);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                isGetAreaId = false;
                Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.tv_areaName:
                showAreaList();
                break;

        }
    }
}
